/*
* created by yq at 2019-08-12
* 注册全局组件
* ps: 该文件注册的组件是基于Vue 和 element,
*     应在上述两者之后引入该文件
*    （如果你确实需要用到该文件中定义的组件）
*/

<template>
<div>
  <el-col v-if="item.type==='divider'" :span="24">
      <el-divider :content-position="item.subtype">{{ item.label }}</el-divider>
  </el-col>
  <el-col v-else :span="item.spannum && item.spannum!=''?item.spannum:6">
    <!-- trigger: item.type==='select'?'change':'blur' -->
    <!-- [{ required: item.required, message: item.label + '不能为空', trigger: 'blur' }] -->
    <el-form-item :rules="Rules"  :label="item.label" :title="item.label" :prop="item.key" :class="{'block':item.block}" :error="item.errorMsg">
      <!--文本框 subtype不同类型-->
      <el-input
        v-if="item.type==='input'"
        v-bind="$attrs"
        v-on="$listeners"
        :type="item.subtype"
        :placeholder="item.placeholder?item.placeholder:((item.disabled || formDisabled)?'':'请输入')"
        :disabled="item.disabled"
        :readonly="item.readonly"
        :autosize="item.autosize">
      </el-input>

      <!--数字框计数器-->
      <el-input-number
        v-else-if="item.type==='number'"
        v-bind="$attrs"
        v-on="$listeners"
        :placeholder="item.placeholder?item.placeholder:((item.disabled || formDisabled)?'':'请输入')"
        :disabled="item.disabled"
        :readonly="item.readonly"
        :autosize="item.autosize"
      ></el-input-number>

      <!--多选框-->
      <el-checkbox
        :disabled="item.disabled"
        v-else-if="item.type==='switch' && item.appearance==='checkbox'"
        v-bind="$attrs"
        v-on="$listeners"
      ></el-checkbox>

      <!--开关-->
      <el-switch
        v-else-if="item.type==='switch'"
        v-bind="$attrs"
        v-on="$listeners"
        :active-value="item.activeValue"
        :inactive-value="item.inactiveValue"
      ></el-switch>

      <!--评分-->
      <el-rate
        v-else-if="item.type==='rate'"
        v-bind="$attrs"
        :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
        text-color="#ff9900"
        v-on="$listeners"
      ></el-rate>

      <!--颜色选择器-->
      <el-color-picker
        v-else-if="item.type==='color'"
        v-bind="$attrs"
        :color-format="item.format"
        v-on="$listeners"
      ></el-color-picker>

      <!--滑块-->
      <el-slider
        v-else-if="item.type==='slider'"
        v-bind="$attrs"
        :range="item.isRange"
        v-on="$listeners"
      ></el-slider>

      <!--单选框组-->
      <el-radio-group
        :disabled="item.disabled"
        v-else-if="item.type==='radio'"
        v-bind="$attrs"
        v-on="$listeners"
      >
        <component
          v-for="o in ajaxOptions"
          :is="item.button?'el-radio-button':'el-radio'"
          :key="o.value"
          :label="o.value"
          :disabled="o.disabled"
          :border="item.border"
        >{{ o.name }}</component>
      </el-radio-group>

      <!--多选框组-->
      <el-checkbox-group
        v-else-if="item.type==='checkbox'"
        v-bind="$attrs"
        v-on="$listeners"
      >
        <component
          v-for="o in ajaxOptions"
          :is="item.button?'el-checkbox-button':'el-checkbox'"
          :key="o.value"
          :disabled="o.disabled"
          :label="o.value"
          :border="item.border"
        >{{ o.name }}</component>
      </el-checkbox-group>

      <!--选择框 -->
      <el-select
        v-else-if="item.type==='select'"
        v-bind="$attrs"
        v-on="$listeners"
        :clearable="true"
        :filterable="true"
        :title="getSelectTitle(ajaxOptions)"
        :multiple="item.subtype == 'multi'?true:false"
        @focus="remoteMethod()"
        @change="selectChange"
        :placeholder="item.placeholder?item.placeholder:((item.disabled || formDisabled)?'':'请选择')">
        <el-option
          v-for="o in ajaxOptions"
          :key="item.valueKey?o[item.valueKey]:o.value?o.value:o.name"
          :label="item.labelKey?o[item.labelKey]:o.name"
          :value="item.valueKey?o[item.valueKey]:o.value?o.value:o.name"
          :code="o.code"
          :disabled="o.disabled"
        >
        </el-option>
      </el-select>

      <!--级联选择器-->
      <el-cascader
        v-else-if="item.type==='cascader'"
        v-bind="$attrs"
        :options="ajaxOptions"
        :clearable="true"
        :title="getSelectTitle(ajaxOptions)"
        :props="{ value:item.valueKey?item.valueKey:'value', label:item.labelKey?item.labelKey:'label', multiple: item.subtype == 'multi'?true:false, checkStrictly: item.checkStrictly}"
        v-on="$listeners"
        :placeholder="item.placeholder?item.placeholder:((item.disabled || formDisabled)?'':'请选择')"
        filterable
        :disabled="item.disabled"
        @focus="remoteMethod()"
      ></el-cascader>

      <!--TimePicker 时间选择器-->
      <el-time-picker
        v-else-if="item.type==='time'"
        :format="item.format ? item.format : 'yyyy-MM-dd HH-mm-ss'"
        v-bind="$attrs"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        v-on="$listeners"
        :disabled="item.disabled"
        :value-format="item.valueFormat ? item.valueFormat : 'yyyy-MM-dd HH-mm-ss'"
      ></el-time-picker>

      <!--DatePicker 日期选择器-->
      <el-date-picker
        v-else-if="item.type==='date'"
        :type="item.subtype"
        :format="item.format ? item.format : 'yyyy-MM-dd'"
        v-bind="$attrs"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        v-on="$listeners"
        :disabled="item.disabled"
        :value-format="item.valueFormat ? item.valueFormat : 'yyyy-MM-dd'"
      ></el-date-picker>

      <!--按钮或按钮组-->
      <el-button
        v-else-if="item.type==='button'"
        :type="item.type"
        :icon="item.icon"
        :disabled="item.disabled"
      >{{item.title}}</el-button>

      <!--按钮组-->
      <el-button-group
        v-else-if="item.type==='buttongroup'"
        v-bind="$attrs"
        v-on="$listeners"
      >
        <el-button
          v-for="o in item.options"
          :key="o.lable"
          :type="o.type"
          :icon="o.icon"
          :disabled="o.disabled"
        >{{o.lable}}</el-button>
      </el-button-group>
      <!--富文本
      <richtext
        v-else-if="item.type==='richtext'"
        v-bind="$attrs"
        v-on="$listeners"
      ></richtext>-->

      <!--upload 文件上传-->
      <el-upload
        class="upload-demo"
        v-else-if="item.type==='upload' && item.subtype==='upload'"
        :action="api[item.uploadUrl]"
        :before-upload="beforeAvatarUpload"
        :on-success="successUpload"
        :on-error="errorUpload"
        :on-remove="removeUpload"
        :headers="headers"
        v-bind="$attrs"
        v-on="$listeners"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>

      <picture-upload
        class="avatar-uploader"
        v-else-if="item.type==='upload' && item.subtype==='picture-img'"
        :disabled="item.disabled"
        :item="item"
        :headers="headers"
        @uploadChange="uploadChange"
        v-bind="$attrs"
        v-on="$listeners"
      >
      </picture-upload>

      <!-- <span v-else>未知控件类型</span> -->

    </el-form-item>
  </el-col>
</div>
</template>
<script>
// import Richtext from '@/components/tinymce';
import { api } from '@/api/common';
import { matchType } from '@/util/upload';
import FormValidate from "@/api/rules.js"
import PictureUpload from '@/components/pictureUpload'
import { isNull } from '@/util/util'
// eslint-disable-next-line 
import { getProvince, getCity, getCounty } from '@/const/views/router/city'
import { getOccupation } from '@/const/views/router/occupation'

export default {
  // components: {
  //   Richtext,
  // },
  components: { PictureUpload },
  props: {
    item: {
      type: Object,
      required: true
    },
    formDisabled: Boolean
  },
  data() {
    return {
      ajaxOptions: this.item.options?this.item.options:[],
      headers:{
        uid:this.$store.getters.userInfo.id,
        token:this.$store.getters.token
      },
      api:api,
    };
  },
  watch: {

  },
  computed: {
    Rules() {
      const rules = this.item.rules
      if (rules === undefined) return undefined
      const R = []
      rules.forEach(rule => {
        if (rule.validator) {
            rule.validator = FormValidate.FormValidate.Form()[rule.validator]
			}
        R.push(rule)
      })
      return R
    }
  },
  created() {
    this.remoteMethod()
  },
  methods: {
    selectChange(val) {
      let _this = this   
      if (_this.item.hasOwnProperty('setCode')) {
        if (val === '') {
          _this.$emit('handelChange', { val: '', key: _this.item.setCode })
        } else {
          for (let index = 0; index < _this.ajaxOptions.length; index++) {
            const element = _this.ajaxOptions[index];
            if (element.name === val) {
              _this.$emit('handelChange', { val: element.code, key: _this.item.setCode })
              break;
            }
          }
        }        
      }
      if (_this.item.hasOwnProperty('setValue')) {
        if (val === '') {
          _this.$emit('handelChange', { val: '', key: _this.item.setValue })
        } else {
          for (let i = 0; i < _this.ajaxOptions.length; i++) {
            let value = ''
            if (_this.item.hasOwnProperty('valueKey')) {
              value = _this.ajaxOptions[i][_this.item.valueKey]
            } else {
              value = _this.ajaxOptions[i].value || _this.ajaxOptions[i].name
            }
            if (value === val) {
              _this.$emit('handelChange', { val: _this.ajaxOptions[i][_this.item.setValueKey], key: _this.item.setValue })
              break;
            }
          }
        }   
      }
    },
    // 远程方式加载下拉款
    remoteMethod() {
      let _this = this
      // eslint-disable-next-line
      const { optionsUrl, optionsCode, code } = _this.item;
      if (!isNull(optionsUrl) && isNull(optionsCode)) {
        let params = {}
        let optionsUrlArr = optionsUrl.split('?')
        if (optionsUrlArr.length > 1) {
          let paramUrl = optionsUrlArr[1]
          let paramUrlArr = paramUrl.split('&')
          for(let i=0;i<paramUrlArr.length;i++){
            var paramArr = paramUrlArr[i].split('=')
            params[paramArr[0]] = paramArr[1]
          }
        }
        if (code === 'OCCUPATION') {
          _this.ajaxOptions = getOccupation()
        } else if (code === 'PROVINCE') {          
          _this.ajaxOptions = getProvince()
        } else if (code === 'CITY') {          
          _this.ajaxOptions = getCity(params)
        } else if (code === 'COUNTY') {          
          _this.ajaxOptions = getCounty(params)
        } else {
          let url = optionsUrlArr[0]
          if (api.hasOwnProperty(optionsUrlArr[0])) {
            url = api[optionsUrlArr[0]]
            _this.axios.post(url, params).then((res) => {
              let _arr = []
              if (_this.item.hasOwnProperty('hasOption')) { // 去除不需要选项
                for (let index = 0; index < _this.item.hasOption.length; index++) {
                  const element = _this.item.hasOption[index];
                  for (let j = 0; j < res.data.data.length; j++) {  
                    let value = _this.item.valueKey?res.data.data[j][_this.item.valueKey]:res.data.data[j].value?res.data.data[j].value:res.data.data[j].name         
                    if (element == value) {
                      _arr.push(res.data.data[j])
                    }
                  }
                }
              } else if (_this.item.hasOwnProperty('extOption')) { // 去除不需要选项
                for (let index = 0; index < _this.item.hasOption.length; index++) {
                  const element = _this.item.hasOption[index];
                  for (let j = 0; j < res.data.data.length; j++) {  
                    let value = _this.item.valueKey?res.data.data[j][_this.item.valueKey]:res.data.data[j].value?res.data.data[j].value:res.data.data[j].name         
                    if (element != value) {
                      _arr.push(res.data.data[j])
                    }
                  }
                }
              } else {
                _arr = res.data.data
              }
              _this.ajaxOptions = _arr;
            }) .catch((err)=>{
              console.log('调用失败',err)
            })
          } else {
            _this.axios.get(optionsUrl, params) .then((res) => {
              console.log(res)
              _this.ajaxOptions = res.data.data;
            }) .catch((err)=>{
              console.log('调用失败',err)
            })
          }  
        }       
      }
    },
    //上传之前操作
    beforeAvatarUpload(file) {
      console.log(file);
      //判断上传文件大小
      if(this.item.size != '' && this.item.size != 0){
        const isLt2M = file.size < this.item.size;
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 '+this.item.size+'KB!');
          return isLt2M
        }
      }
      //判断上传文件类型
      if(this.item.fileType.length > 0){
        let matchFileType = matchType(file.name)
        const isFileType = matchFileType.indexOf(this.item.fileType.join(',')) != -1
        if (!isFileType) {
          this.$message.error('上传文件格式不正确!');
          return isFileType
        }
      }
      
      return true
    },
    successUpload(response, file, fileList) {
      console.log(response);
      if(response.code === 10000){
        this.$message.success(response.message);
        this.$set(file, 'src', response.data.src)
        this.$emit('handelChange',{ key: this.item.key, val: [{name: file.name, url:response.data.key}], item: this.item, data: response.data })
        if (this.item.hasOwnProperty('setValue')) {
          this.$emit('handelChange',{ key: this.item.setValue, val: response.data[this.item.setValueKey] })
        }
        //单文件上传覆盖fileList
        // if(!this.item.multiple){
        //   fileList.splice(1);
        //   fileList[0] = Object.assign({}, fileList[0], file)
        // }else{
        //   fileList[fileList.length-1] = Object.assign({}, fileList[fileList.length-1], file)
        // }
      }else{
        this.$message.error(response.message);
      }
    },
    removeUpload() {
      this.$emit('handelChange',{ key: this.item.key, val: '', item: this.item })
      if (this.item.hasOwnProperty('setValue')) {
        this.$emit('handelChange',{ key: this.item.setValue, val: '' })
      }
    },
    errorUpload(err) {
      console.log(err);
      this.$message.error(err);
    },
    uploadChange(data) {
      console.log(data)
      this.$emit('handelChange',data)
    },
    getSelectTitle (roptions) {
      for (let i = 0; i < roptions.length; i++) {
        let val = '',
          name = ''
        if (this.item.hasOwnProperty('valueKey')) {
          val = roptions[i][this.item.valueKey]
        } else {
          val = roptions[i].value || roptions[i].name
        }
        if (this.$attrs.value === val) {
          if (this.item.hasOwnProperty('labelKey')) {
            name = roptions[i][this.item.labelKey]
          } else {
            name = roptions[i].name
          }
          return name
        }
      }
    }
  }
}
</script>

<style>
.block {
  display: block !important;
  display: flex !important;
}
</style>